﻿#include"Logger.hpp"


namespace MMFLogger{


Logger::Logger()
{
    //创建buffer
    mBuffers.resize(4);
    for (int i = 0; i < mBuffers.size(); i++)
        mBuffers[i] = new Buffer(512 * 1024, 3600ull * 1000000ull);

    //当前使用的缓存为第0个
    mCurBuffer = 0;
}


Logger::~Logger()
{
    //停止接收数据
    mCurBuffer = -1;

    //释放内存
    for (int i = 0; i < mBuffers.size(); i++)
    {
        delete mBuffers[i];
        mBuffers[i] = nullptr;
    }
}

void Logger::PushLog(const char* log, uint32_t size)
{
    mMutex.Lock();

    //写入数据
    int bufferIdx = mCurBuffer % mBuffers.size();
    uint32_t writeSize = mBuffers[bufferIdx]->Write(log, size);

    if (writeSize == size)
    {
        mMutex.Unlock();
        return;
    }

    //剩下的循环三遍如果都没写入就丢弃了
    for (int i = 0; i < mBuffers.size() - 1; i++)
    {
        mCurBuffer++;
        bufferIdx = mCurBuffer % mBuffers.size();
        uint32_t lastSize = size - writeSize;
        uint32_t lastWriteSize = mBuffers[bufferIdx]->Write(log + writeSize, lastSize);
        writeSize += lastWriteSize;
        if (lastWriteSize == lastSize)
            break;
    }

    mMutex.Unlock();
}

void Logger::PushLog(const std::string& log)
{
    PushLog(log.data(), (uint32_t)log.length());
}


}